package ua.kratik.seabattle.web;

import java.util.Map;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ua.kratik.seabattle.game.Admiral;

public class SessionListener implements HttpSessionListener{

	private static Logger logger = LoggerFactory.getLogger(SessionListener.class);

	private int sessionCount = 0;

	public void sessionCreated(HttpSessionEvent event){
		synchronized (this) {
			sessionCount++;
		}
		System.out.println("Session Created: " + event.getSession().getId());
		System.out.println("Total Sessions: " + sessionCount);
	}

	/**
	 * delete user from Servlet context if user exists
	 */
	public void sessionDestroyed(HttpSessionEvent event) {
		synchronized (this) {
			sessionCount--;
		}
		System.out.println("Session Destroyed: " + event.getSession().getId());
		System.out.println("Total Sessions: " + sessionCount);

		// check if user is valid
		Object obj = event.getSession().getAttribute("admiral");
		// if user was logged in
		if (obj != null) {
			Admiral admiral = (Admiral)obj;
			obj = event.getSession().getServletContext().getAttribute("loggedAdmirals");
			if (obj == null) {
				logger.error("Servlet context attribute 'loggedAdmirals' was not created");
			}else{
				Map<String, Admiral> loggedAdmirals = (Map<String, Admiral>) obj;
				loggedAdmirals.remove(admiral);
			}
		}

	}
}